<template>
    <div>
        <Modal
            v-model="show.modal"
            :title="title"
            :loading="loading"
            :mask-closable="false"
            @on-ok="submitShareTree"
            @on-cancel=""
            footer-hide
            width="900"
        >
            <Row>
                <Col span="11">
                    <div style="display: flex;justify-content: space-between;margin-bottom:10px;">
                        <h4 style="flex:none">已生成技能树列表</h4>
                        <Tooltip
                            v-if="curSkill && curSkill.name"
                            class="tree-name-tooltip"
                            :content="curSkill && curSkill.name"
                            :max-width="200"
                        >
                            <p class="name" :title="curSkill && curSkill.name">
                                当前选中:{{ curSkill && curSkill.name }}
                            </p>
                        </Tooltip>
                    </div>
                    <Table
                        :data="treeList"
                        :columns="treeCol"
                        @on-expand="getShareRoleList"
                    ></Table>
                    <Page
                        style="text-align: center;margin-top:10px;"
                        :total="treeTotal"
                        show-total
                        show-elevator
                        :current="queryTreeInfo.pageIndex"
                        :page-size="queryTreeInfo.pageSize"
                        @on-change="changePage"
                    ></Page>
                </Col>
                <Col span="12" offset="1">
                    <div style="display: flex;justify-content: space-between;margin-bottom:10px;">
                        <h4>岗位列表</h4>
                        <Checkbox v-model="queryRoleInfo.isShare" @on-change="changeRolePage(1)"
                            >已分享</Checkbox
                        >
                    </div>
                    <Table :data="showRoleList" :columns="roleCol"></Table>
                    <Page
                        style="text-align: center;margin-top:10px;"
                        :total="roleTotal"
                        show-total
                        show-elevator
                        :current="queryRoleInfo.pageIndex"
                        :page-size="queryRoleInfo.pageSize"
                        @on-change="changeRolePage"
                    ></Page>
                </Col>
            </Row>
        </Modal>
        <!-- <Drawer v-model="show.drawer" :title="title" width="700">
            <div class="table-wrapper">
                <Table :data="treeList" :columns="treeCol" @on-expand="getShareRoleList"></Table>
                <Page
                    style="text-align: center;margin-top:10px;"
                    show-total
                    :total="treeTotal"
                    :current="queryTreeInfo.pageIndex"
                    :page-size="queryTreeInfo.pageSize"
                    @on-change="changePage"
                ></Page>
            </div>
        </Drawer>
        <Drawer v-model="show.role" title="已推荐岗位列表" width="600">
            <Table :data="roleList" :columns="roleCol"></Table>
            <Page
                style="text-align: center;margin-top:10px;"
                show-total
                :total="roleTotal"
                :current="queryRoleInfo.pageIndex"
                :page-size="queryRoleInfo.pageSize"
                @on-change="changePage"
            ></Page>
        </Drawer> -->
        <show-tree-detail ref="treeDetail"></show-tree-detail>
    </div>
</template>
<script>
import {
    getTreeListByExcellentUser,
    shareTree,
    unShareTree,
    getShareRoleList
} from '@/api/selfStudy/skill';
import { queryRole } from '@/api/role.js';
import ShowTreeDetail from '@/view/experimentalScene/skillTree/showTreeDetail.vue';
import SkillTree from '@/view/experimentalScene/skillTree/skillTree.vue';
export default {
    name: 'shareModal',
    components: { ShowTreeDetail, SkillTree },
    props: {
        value: {
            type: Boolean,
            default: false
        },
        type: {
            type: String,
            default: 'share'
        },
        userId: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            curSkill: {id:'',name:''},
            show: {
                drawer: this.value || false,
                modal: this.value || false,
                role: false
            },
            loading: true,
            title: '分享/取消分享技能树',
            rules: {
                skillId: [
                    {
                        required: true,
                        message: '请选择技能树',
                        trigger: 'change'
                    }
                ],
                roleId: [
                    {
                        required: true,
                        message: '请选择岗位角色',
                        trigger: 'change'
                    }
                ]
            },
            queryTreeInfo: {
                pageIndex: 1,
                pageSize: 10
            },
            treeList: [],
            treeTotal: 0,
            totaled:0,
            treeCol: [
                {
                    // type:'selection',
                    title: '',
                    width: 52,
                    key: 'id',
                    align: 'left',
                    ellipsis: false,
                    tooltip: false,
                    render: (h, params) => {
                        let { id, name } = params.row;
                        return h('Radio', {
                            props: {
                                value: this.curSkill.id === params.row.id,
                                disabled: params.row.available == 0
                            },
                            class: 'table-radio',
                            style: {
                                margin: 0
                            },
                            on: {
                                'on-change': (e) => {
                                    params.row._checked = e;
                                    this.curSkill = params.row;
                                    this.queryRoleInfo.pageIndex = 1;
                                    this.getRoleList();
                                    this.getShareRoleList();
                                }
                            }
                        });
                    }
                },
                {
                    title: '名称',
                    key: 'name',
                    tooltip: true,
                    render: (h, params) => {
                        return h(
                            'a',
                            {
                                on: {
                                    click: (e) => {
                                        this.$refs.treeDetail.open(params.row);
                                    }
                                }
                            },
                            params.row.name
                        );
                    }
                },
                {
                    title: '可用状态',
                    key: 'available',
                    tooltip: true,
                    width:90,
                    render:(h,params) => {
                        return h('span',params.row.available == 0 ? '不可用' : '可用')
                    }
                }
            ],
            queryRoleInfo: {
                pageIndex: 1,
                pageSize: 10,
                isShare: false
            },
            roleList: [],
            roleTotal: 0,
            shareRoleList: [], //已分享角色列表
            roleCol: [
                {
                    title: '岗位名称',
                    key: 'name',
                    tooltip: true
                },
                {
                    title: '操作',
                    key: 'action',
                    width: 160,
                    render: (h, params) => {
                        return h('div', [
                            h(
                                'Button',
                                {
                                    props: {
                                        type: 'primary',
                                        size: 'small',
                                        disabled: !this.curSkill.id || this.shareRoleIdList.includes(params.row.id)
                                    },
                                    style: {
                                        'margin-right': '4px'
                                    },
                                    on: {
                                        click: (e) => {
                                            this.shareTree(params.row.id);
                                        }
                                    }
                                },
                                '分享'
                            ),
                            h(
                                'Poptip',
                                {
                                    props: {
                                        transfer: true,
                                        confirm: true,
                                        title: '确认取消分享?'
                                    },
                                    on: {
                                        'on-ok': (e) => {
                                            this.unShareTree(params.row.id);
                                        }
                                    }
                                },
                                [
                                    h(
                                        'Button',
                                        {
                                            props: {
                                                type: 'primary',
                                                size: 'small',
                                                disabled: !this.curSkill.id || !this.shareRoleIdList.includes(
                                                    params.row.id
                                                )
                                            }
                                        },
                                        '取消分享'
                                    )
                                ]
                            )
                        ]);
                    }
                }
            ]
        };
    },
    mounted(){
         this.queryRoleInfo.isShare=false
    },
    computed: {
        shareRoleIdList() {
            return this.shareRoleList.map((role) => role.roleId);
        },
        showRoleList() {
            let list = [];
            if (this.queryRoleInfo.isShare) {
                list = this.shareRoleList.slice(
                    (this.queryRoleInfo.pageIndex - 1) * this.queryRoleInfo.pageSize,
                    this.queryRoleInfo.pageIndex * this.queryRoleInfo.pageSize
                );
                list.forEach((role) => {
                    role.id = role.roleId;
                });
                if(this.queryRoleInfo.isShare){
                    this.roleTotal=this.totaled
                }else{
                     this.roleTotal = this.shareRoleList.length;
                }
            } else {
                list = this.roleList;
            }
            return list;
        }
    },
    watch: {
        show: {
            handler(val) {
                 this.queryRoleInfo.isShare=false
                if (!val.modal || !val.drawer) {
                    this.$emit('input', false);
                    this.$emit('close');
                }
            },
            deep: true
        },
        value(val) {
            if (val) {
                this.showModal();
            } else {
                if (this.type === 'share') {
                    this.show.drawer = false;
                } else {
                    this.show.modal = false;
                }
            }
        }
    },
    methods: {
        async showModal() {
            this.treeList = [];
            this.treeTotal = 0;
            this.roleList = [];
            this.roleTotal = 0;
            this.shareRoleList = [];
            this.curSkill = {id:'',name:''};
            this.queryTreeInfo.pageIndex = 1;
            this.queryRoleInfo.pageIndex = 1;
            const msg = this.$Message.loading({
                content: '正在请求技能树数据...',
                duration: 0
            });
            await this.getTreeList().catch(error => {
                setTimeout(msg);
            });
            setTimeout(msg);
            if(this.treeList.length == 0){
                this.$Message.warning('请先生成技能树')
                this.$emit('input', false);
                this.$emit('close');
                setTimeout(msg);
                return
            }else{
                this.curSkill = this.treeList.find(tree => tree.available == 1) || {id:'',name:''};
                this.getRoleList();
                if(this.curSkill.id){
                    this.getShareRoleList();
                }
            }
            this.show.modal = true;
        },
        // 获取优秀学员生成的技能树列表
        getTreeList() {
            return new Promise((resolve,reject) => {
                 getTreeListByExcellentUser(this.userId, this.queryTreeInfo)
                .then(({ code, data, message }) => {
                    if (code === 1) {
                        this.treeList = data.items;
                        this.treeTotal = data.total;
                    } else {
                        this.treeList = [];
                        this.treeTotal = 0;
                        this.$Message.error(message);
                    }
                    resolve();
                })
                .catch((error) => {
                    this.$Message.error('获取技能树数据失败')
                    reject();
                });
            });
        },
        changePage(page) {
            this.queryTreeInfo.pageIndex = page;
            this.getTreeList();
        },
        changeRolePage(page) {
            this.queryRoleInfo.pageIndex = page;
            if (!this.queryRoleInfo.isShare) {
                this.getRoleList();
            }
        },
        // 获取所有岗位角色列表
        getRoleList() {
            this.roleList = [];
            this.roleTotal = 0;
            let { pageIndex, pageSize } = this.queryRoleInfo;
            let params = {
                pageIndex,
                pageSize
            };
            queryRole(params).then((res) => {
                let { code, data, message } = res.data;
                if (code === 1) {
                    this.roleList = data.items;
                    this.roleTotal = data.total;
                } else {
                    this.$Message.error(message);
                }
            });
        },
        // 根据优秀学员id和树id获取已分享的岗位列表
        getShareRoleList() {
            let params = {};
            params.skillId = this.curSkill.id;
            params.sourceId = this.userId;
            params.pageIndex = 1;
            params.pageSize = 99999;
            getShareRoleList(params).then(({ code, data, message }) => {
                if (code === 1) {
                    this.shareRoleList = data.items;
                    this.totaled=data.total
                } else {
                    this.$Message.error(message);
                }
            });
        },
        // 分享
        submitShareTree() {
            this.$refs['form']
                .validate((valid) => {
                    if (valid) {
                        this.shareTree();
                    } else {
                        this.cancelLoading();
                    }
                })
                .catch((error) => {
                    this.cancelLoading();
                });
        },
        shareTree(roleId) {
            let data = { skillId: this.curSkill.id, roleId: roleId, sourceId: this.userId };
            shareTree(data).then(({ code, data, message }) => {
                if (code === 1) {
                    this.$Message.info('分享成功');
                    this.getShareRoleList('all');
                    // this.show.modal = false;
                } else {
                    this.$Message.error(message);
                }
                // this.cancelLoading();
            });
        },
        unShareTree(roleId) {
            unShareTree(roleId, this.userId).then(({ code, data, message }) => {
                if (code === 1) {
                    this.$Message.info('取消分享成功');
                    if (
                        this.showRoleList.length == 1 &&
                        this.queryRoleInfo.isShare &&
                        this.queryRoleInfo.pageIndex > 1
                    ) {
                        this.queryRoleInfo.pageIndex--;
                    }
                    this.getShareRoleList(this.currentTree);
                } else {
                    this.$Message.error(message);
                }
            });
        },
        cancelLoading() {
            this.loading = false;
            setTimeout(() => {
                this.loading = true;
            });
        }
    }
};
</script>
<style scoped>
.table-wrapper {
    height: 100%;
}
</style>
<style>
.table-radio .ivu-radio {
    margin: 0;
}
.tree-name-tooltip {
    height: 18px;
    margin-left: 20px;
    overflow: hidden;
}
.tree-name-tooltip .ivu-tooltip-rel {
    width: 100%;
}
.tree-name-tooltip .name {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
</style>
